package top.yuhaitao.core.util;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

public class OkhttpUtil {

    private static final Logger log = LoggerFactory.getLogger(OkhttpUtil.class);

    public static String httpGet(String url) throws IOException {
        Response response = null;
        try {
            OkHttpClient client = new OkHttpClient().newBuilder().connectTimeout(10, TimeUnit.SECONDS).readTimeout(20, TimeUnit.SECONDS).build();
            Request request = new Request.Builder()
                    .url(url)
                    .get()
                    .build();
            response = client.newCall(request).execute();
            if (response.isSuccessful()) {
                String retJson = response.body().string();
                if (log.isDebugEnabled()) {
                    log.debug("http-url:{}，response:{}", url, retJson);
                }
                return retJson;
            }
            throw new RuntimeException("http error");
        } finally {
            if (response != null) {
                response.close();
            }
        }


    }
}
